// signaling-server.js
const WebSocket = require('ws');
const http = require('http');
const url = require('url');
const querystring = require('querystring');

// 设备认证信息存储 (实际项目中应该使用数据库)
const devices = {
  'service-smp1': { username: 'smp1', password: 'smp1' }
};

// 创建HTTP服务器
const server = http.createServer();
const wss = new WebSocket.Server({ server });

// 存储连接的客户端和设备
const clients = {};
const deviceConnections = {};

wss.on('connection', (ws, req) => {
  const query = url.parse(req.url).query;
  const params = querystring.parse(query);
  
  // 验证设备或用户
  if (params.type === 'device') {
    // 设备连接
    const deviceId = params.deviceId;
    if (devices[deviceId]) {
      deviceConnections[deviceId] = ws;
      console.log(`设备 ${deviceId} 已连接`);
      
      ws.on('close', () => {
        delete deviceConnections[deviceId];
        console.log(`设备 ${deviceId} 已断开`);
      });
    }
  } else if (params.type === 'client') {
    // 用户连接
    const deviceId = params.deviceId;
    const username = params.username;
    const password = params.password;
    
    if (devices[deviceId] && 
        devices[deviceId].username === username && 
        devices[deviceId].password === password) {
      
      const clientId = `${deviceId}-${Date.now()}`;
      clients[clientId] = ws;
      console.log(`客户端 ${clientId} 已连接`);
      
      // 转发信令消息
      ws.on('message', (message) => {
        const msg = JSON.parse(message);
        if (msg.target === 'device' && deviceConnections[deviceId]) {
          deviceConnections[deviceId].send(JSON.stringify(msg.data));
        }
      });
      
      ws.on('close', () => {
        delete clients[clientId];
        console.log(`客户端 ${clientId} 已断开`);
      });
    } else {
      ws.close(1008, '认证失败');
    }
  }
});

server.listen(8080, () => {
  console.log('信令服务器运行在 ws://localhost:8080');w
});